package com.seng.resourcetycoon.manager;

import com.seng.resourcetycoon.core.entities.RandomEvent;
import com.seng.resourcetycoon.event.RandomEventListener;
import com.seng.resourcetycoon.gui.util.EventGenerator;
import com.seng.resourcetycoon.services.GamePlayService;
import com.seng.resourcetycoon.services.GameStateHandler;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;

import java.util.ArrayList;
import java.util.List;

public class EventManager implements GameStateHandler {
    private Timeline timeline = null;
    private static EventManager instance;
    private final List<RandomEventListener> listeners;
    private final EventGenerator eventGenerator;

    private EventManager() {
        listeners = new ArrayList<>();
        eventGenerator = new EventGenerator();
        timeline = new Timeline(
                new KeyFrame(Duration.seconds(12),
                        event -> {
                            instance.notifyListeners(eventGenerator.generateEvent(GameEnvironment.getInstance().getDifficultyLevel(), GameEnvironment.getInstance().getGameRound()));
                        })
        );
        timeline.setCycleCount(Timeline.INDEFINITE); // 循环执行
        timeline.play();
    }


    public static EventManager getInstance() {
        if (instance == null) {
            instance = new EventManager();
        }

        return instance;
    }

    private void registerListener(RandomEventListener listener) {
        listeners.add(listener);
    }

    private void unregisterListener(RandomEventListener listener) {
        listeners.remove(listener);
    }

    @Override
    public void initialize(GamePlayService gamePlayService) {
        registerListener(gamePlayService);
    }

    @Override
    public void begin() {
        timeline.play();
    }

    @Override
    public void suspend() {
        timeline.pause();
    }

    @Override
    public void continueProcessing() {
        timeline.play();
    }

    @Override
    public void cleanup(GamePlayService gamePlayService) {
        unregisterListener(gamePlayService);
        timeline.stop();
    }

    public void notifyListeners(RandomEvent event) {
        for (RandomEventListener listener : listeners) {
            listener.onRandomEvent(event);
        }
    }
}
